import {
  MenuFoldOutlined,
  MenuUnfoldOutlined
} from '@ant-design/icons';
import { Button, Layout, Menu, theme, Modal } from 'antd';
import { useState, useEffect } from 'react';
import './Welcome.css'
import Routes from '@/routes/index'
import { Link, useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { useLocation } from 'react-router-dom'
import axios from '@/api/axios';
import { useDispatch, useSelector } from 'react-redux';
import { saveToken, saveMenus } from '@/store/userSlice'


const { Header, Sider, Content } = Layout;
const App = () => {

  let loc = useLocation()
  let dispatch = useDispatch()
  let history = useHistory()
  let newMenus = useSelector((state) => state.user.menus || [])



  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('acl')
    dispatch(saveToken(''))
    dispatch(saveMenus([]))
    setIsModalOpen(false);
    history.push('/login')
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const [collapsed, setCollapsed] = useState(false);
  const [accountInfo, setAccountInfo] = useState({});
  const [items, setItems] = useState([])
  const [isLogin, setIsLogin] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  function getItem(label, key, icon, children) {
    return {
      key,
      icon,
      children,
      label,
    };
  }

  const mapMenus = newMenus.map(item => {
    if (item.children.length > 0) {
      return getItem(item.auth_name, item.auth_path, null,
        item.children.map(child => {
          if (child.is_nav === 1) {
            return getItem(<Link to={child.auth_path}>{child.auth_name}</Link>, child.auth_path, null)
          }
        })
      )
    } else {
      return getItem(<Link to={item.auth_path}>{item.auth_name}</Link>, item.auth_path, null)
    }
  })


  useEffect(() => {
    axios.get('/common/auth/jwtPreCheck').then(res => {
      if (res.data.errNo === 0) {
        setItems(mapMenus)
        setIsLogin(true)
        axios.get('/common/auth/adminInfo').then(res => {
          if (res.data.errNo === 0) {

            setAccountInfo(res.data.accountInfo)
          }
        })
      } else {
        history.push('/login')
      }
    })

  }, [])



  return (
    <>
      {isLogin && <Layout>
        <Sider trigger={null} collapsible collapsed={collapsed}>
          <div className="demo-logo-vertical" />
          <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={[loc.pathname]}
            defaultOpenKeys={[loc.pathname.substring(0, loc.pathname.lastIndexOf('/'))]}
            items={items}
          />
        </Sider>
        <Layout>
          <Header
            style={{
              padding: 0,
              background: colorBgContainer,
            }}
          >
            <div className="header">
              <div>
                <Button
                  type="text"
                  icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                  onClick={() => setCollapsed(!collapsed)}
                  style={{
                    fontSize: '16px',
                    width: 64,
                    height: 64,
                  }}
                />
                <span>欢迎：{accountInfo.username}/{accountInfo.role}</span>
              </div>

              <div onClick={showModal}>注销登录</div>
              <Modal title="提醒！" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <p>你确定要注销账户并退出登录么？</p>
              </Modal>
            </div>

          </Header>
          <Content
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280,
              background: colorBgContainer,
            }}
          >
            <Routes />
          </Content>
        </Layout>
      </Layout>}
    </>

  );
};
export default App;